const { Configuration, OpenAIApi } = require('openai')

const apiKey = 'sk-proj-dVdrActQ2aROVSQqogsaT3BlbkFJwnYVnDWK2eTgKbD3W99e'

const configuration = new Configuration({
  apiKey
})

const openAIApi = new OpenAIApi(configuration)

// 处理给 ChatGPT 的数据
const promps = {}

function savePrompt(fromusername, content) {
  if (promps[fromusername]) {
    // 存在，添加数据
    promps[fromusername].push({
      role: 'user',
      content
    })
  } else {
    // 不存在，新建一个用户的数据
    promps[fromusername] = [
      {
        role: 'user',
        content
      }
    ]
  }
  return promps[fromusername]
}
// 返回问题答案
async function getCompletions(fromusername, content) {
  const messages = savePrompt(fromusername, content)

  const completion = await openAIApi.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages,
    temperature: 0,
    max_tokens: 256,
    top_p: 1
  })

  console.log(completion.data.choices[0]['message']['content'])
  return completion.data.choices[0].message.content
}

module.exports = getCompletions